<?php
namespace addons\tencentoss;

use think\Addons;
use think\facade\Db;
use app\common\annotation\HooksAnotation;
use app\member\service\User as home_user;
use app\admin\model\Attachment as Attachment_Model;

class Plugin extends Addons
{
    // 该插件的基础信息
    public $info = [
        'name' => 'tencentoss',
        'title' => '腾讯云oss插件',
        'description' => '腾讯云oss插件',
        'status' => 1,
        'author' => 'ZengCMS',
        'require' => '1.0.0',
        'version' => '1.0.0',
        'website' => '',
        'images'=>'addons/tencentoss/images/tencentoss.jpg',
        'group'=>'',
        'is_hook'=>1,
    ];
    public $menu = [
        'is_nav' => 0,
    ];
    // 上传管理员ID
    public $admin_id = 0;
    // 上传用户ID
    public $user_id  = 0;
    // 会员组
    public $groupid = 0;
    // 是否后台
    public $isadmin     = 0;
    // 插件配置
    public $config = array();
    // 初始化
    protected function init()
    {
        // 判断是否安装
        if(!isAddonInstall($this->name)){
            return false;
        }
        include_once ADDONS_PATH . '/tencentoss/SDK/vendor/autoload.php';
        $this->isLogin();
        $this->config = getAddonConfig('tencentoss');
    }
    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $upload_driver = Db::name('config')->where(['name' => 'upload_driver'])->find();
        if (!$upload_driver) {
            $this->error = '未找到【上传驱动】配置';
            return false;
        }
        $options = parse_attr($upload_driver['extra']);
        if (isset($options['tencentoss'])) {
            $this->error = '已存在名为【tencentoss】的上传驱动';
            return false;
        }
        $upload_driver['extra'] .= PHP_EOL . 'tencentoss:腾讯云oss';
        $result = Db::name('config')
        ->where(['name' => 'upload_driver'])
        ->update(['extra'=>$upload_driver['extra']]);
        if (false === $result) {
            $this->error = '上传驱动设置失败';
            return false;
        }
        return true;
    }
    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        $upload_driver = Db::name('config')->where(['name' => 'upload_driver'])->find();
        if ($upload_driver) {
            $options = parse_attr($upload_driver['extra']);
            if (isset($options['tencentoss'])) {
                unset($options['tencentoss']);
            }
            $options = $this->implode_attr($options);
            $result  = Db::name('config')
            ->where(['name' => 'upload_driver'])
            ->update(['extra' => $options, 'value' => $upload_driver['value'] == 'tencentoss'?'local':$upload_driver['value']]);
            if (false === $result) {
                $this->error = '上传驱动设置失败';
                return false;
            }
        }
        return true;
    }
    /**
     * 插件使用方法
     * @return bool
     */
    public function enabled()
    {
        return true;
    }
    /**
     * 插件禁用方法
     * @return bool
     */
    public function disabled()
    {
        return true;
    }
    /**
     * name 钩子(行为)名称
     * description 钩子描述
     * type 类型(1:视图,2:控制器)
     * system 是否系统
     * status 状态
     * @HooksAnotation(description="上传附件",type="2")
     * @return [type] [description]
     */
    public function UploadOssAfter($params = [])
    {
        // 判断是否调用腾讯云的
        if(sys_config('upload_driver') !== 'tencentoss'){
            return '';
        }
        $this->init();
        $file   = $params['file'];
        $error_msg = '';
        if ($this->config['SecretId'] == '') {
            $error_msg = '未填写腾讯云oss【SecretId】';
        } elseif ($this->config['SecretKey'] == '') {
            $error_msg = '未填写腾讯云oss【SecretKey】';
        } elseif ($this->config['bucket'] == '') {
            $error_msg = '未填写腾讯云oss【bucket】';
        } elseif ($this->config['region'] == '') {
            $error_msg = '未填写腾讯云oss【region】';
        }
        if ($error_msg != '') {
            return json_encode([
                'code'    => -1,
                'info'    => $error_msg,
                'state'   => $error_msg,// 兼容百度ueditor
                'error'   => 1,         // 兼容kindeditor
                'success' => 0,         // 兼容editormd
                'message' => $error_msg,// 兼容editormd和kindeditor
            ],JSON_UNESCAPED_UNICODE);
        }
        $info['name'] = $file->getOriginalName();
        $info['mime'] = $file->getOriginalMime();
        $info['tmp_name'] = $file->getPathName();
        $suffix = strtolower(pathinfo($info['name'], PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        // 要上传文件的本地路径
        $filePath = $info['tmp_name'];
        // 上传到七牛后保存的文件名
        $file_name = explode('.', $info['name']);
        $ext       = end($file_name);
        $key       = $params['dir'] . '/' . date('Ymd') . '/' . $file->hash('md5') . '.' . $ext;
        try {
            $cosClient = new \Qcloud\Cos\Client(
                array(
                    'region' => $this->config['region'],
                    'schema' => 'https',//协议头部，默认为http
                    'credentials'=> array(
                        'secretId'  => $this->config['SecretId'],
                        'secretKey' => $this->config['SecretKey']
                    )
                )
            );
            $bucket = $this->config['bucket'] . '-' . $this->config['APPID']; //存储桶名称 格式：BucketName-APPID
            $filep = fopen($filePath, "rb");
            if ($filep) {
                $result = $cosClient->putObject(
                    array(
                        'Bucket' => $bucket,
                        'Key' => $key,
                        'Body' => $filep
                    )
                );
                $upload_success = false;
                // 请求成功
                $data = $result->toArray() ;
                if(isset($data['Location']) && isset($data['Key'])){
                    $img_url = $data['Location'];
                    $upload_success = true;
                }
                if($upload_success){
                    // 获取附件信息
                    $path = 'https://' . $img_url;
                    $file_type = get_file_type_for_ext($suffix);
                    $data = [
                        'aid'    => $this->admin_id,
                        'uid'    => $this->user_id,
                        'group_id'    => $params['group_id']??0,
                        'file_name'=>basename($path),
                        'file_type'=>$file_type,
                        'name'   => $info['name'],
                        'module' => $params['module'],
                        'path'   => $path,
                        'thumb'  => '',
                        'url'    => '',
                        'mime'   => $info['mime'],
                        'ext'    => $suffix,
                        'size'   => $file->getSize(),
                        'md5'    => $file->hash('md5'),
                        'sha1'   => $file->hash('sha1'),
                        'driver' => 'aliyunoss',
                        'status'      => 1,
                        'sort'        => 100,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                    if ($file_add = Attachment_Model::create($data)) {
                        // 返回结果
                        return json_encode([
                            'code'    => 0,
                            'info'    => $data['name'] . '上传成功',
                            'id'      => $file_add['id'],
                            'path'    => $data['path'],
                            'state'   => "SUCCESS",     // 上传状态，上传成功时必须返回"SUCCESS" 兼容百度
                            'url'     => $data['path'], // 返回的地址 兼容百度ueditor和kindeditor
                            'title'   => $data['name'], // 附件名 兼容百度ueditor
                            'error'   => 0,             // 兼容kindeditor
                            'success' => 1,             // 兼容editormd
                            'message' => $data['name'], // 附件名 兼容editormd和kindeditor
                        ],JSON_UNESCAPED_UNICODE);
                    } else {
                        return json_encode([
                            'code'    => -1,
                            'info'    => '上传成功,写入数据库失败',
                            'state'   => '上传成功,写入数据库失败', //兼容百度ueditor
                            'error'   => 1,                       //兼容kindeditor
                            'success' => 0,                       //兼容editormd
                            'message' => '上传成功,写入数据库失败', //兼容editormd和kindeditor
                        ],JSON_UNESCAPED_UNICODE);
                    }
                }else{
                    return json_encode([
                        'code'    => -1,
                        'info'    => '上传失败',
                        'state'   => '上传失败', //兼容百度ueditor
                        'error'   => 1,         //兼容kindeditor
                        'success' => 0,         //兼容editormd
                        'message' => '上传失败', //兼容editormd和kindeditor
                    ]);
                }
            } else {
                return json_encode([
                    'code'    => -1,
                    'info'    => '上传失败',
                    'state'   => '上传失败', //兼容百度ueditor
                    'error'   => 1,         //兼容kindeditor
                    'success' => 0,         //兼容editormd
                    'message' => '上传失败', //兼容editormd和kindeditor
                ]);
            }
		} catch (\Exception $e) {
            return json_encode([
                'code'    => -1,
                'info'    => '上传失败:' . $e->getMessage(),
                'state'   => '上传失败:' . $e->getMessage(),//兼容百度ueditor
                'error'   => 1,                            //兼容kindeditor
                'success' => 0,                            //兼容editormd
                'message' => '上传失败:' . $e->getMessage(),//兼容editormd和kindeditor
            ]);
        }
    }
    /**
     * name 钩子(行为)名称
     * description 钩子描述
     * type 类型(1:视图,2:控制器)
     * system 是否系统
     * status 状态
     * @HooksAnotation(description="上传本地附件",type="2")
     * @return [type] [description]
     */
    public function UploadOss($params = [])
    {
        // 判断是否调用腾讯云的
        if(sys_config('upload_driver') !== 'tencentoss'){
            return '';
        }
        $this->init();
        $error_msg = '';
        if ($this->config['SecretId'] == '') {
            $error_msg = '未填写腾讯云oss【SecretId】';
        } elseif ($this->config['SecretKey'] == '') {
            $error_msg = '未填写腾讯云oss【SecretKey】';
        } elseif ($this->config['bucket'] == '') {
            $error_msg = '未填写腾讯云oss【bucket】';
        } elseif ($this->config['region'] == '') {
            $error_msg = '未填写腾讯云oss【region】';
        }
        if ($error_msg != '') {
            return json_encode([
                'code'    => -1,
                'info'    => $error_msg,
                'state'   => $error_msg, // 兼容百度ueditor
                'error'   => 1,          // 兼容kindeditor
                'success' => 0,          // 兼容editormd
                'message' => $error_msg, // 兼容editormd和kindeditor
            ],JSON_UNESCAPED_UNICODE);
        }
        $key = str_replace('uploads/', '', $params['path']);
        try {
            $cosClient = new \Qcloud\Cos\Client(
                array(
                    'region' => $this->config['region'],
                    'schema' => 'https',//协议头部，默认为http
                    'credentials'=> array(
                        'secretId'  => $this->config['SecretId'],
                        'secretKey' => $this->config['SecretKey']
                    )
                )
            );
            $result = $cosClient->upload(
                $bucket = $this->config['bucket'] . '-' . $this->config['APPID'],//格式：BucketName-APPID
                $key = $key,
                $body = fopen(get_file_path($params['path'],2), 'rb')
                /*
                $options = array(
                    'ACL' => 'string',
                    'CacheControl' => 'string',
                    'ContentDisposition' => 'string',
                    'ContentEncoding' => 'string',
                    'ContentLanguage' => 'string',
                    'ContentLength' => integer,
                    'ContentType' => 'string',
                    'Expires' => 'string',
                    'GrantFullControl' => 'string',
                    'GrantRead' => 'string',
                    'GrantWrite' => 'string',
                    'Metadata' => array(
                        'string' => 'string',
                    ),
                    'ContentMD5' => 'string',
                    'ServerSideEncryption' => 'string',
                    'StorageClass' => 'string'
                )
                */
            );
            $upload_success = false;
            // 请求成功
            $data = $result->toArray() ;
            if(isset($data['Location']) && isset($data['Key'])){
                $img_url = $data['Location'];
                $upload_success = true;
            }
            if($upload_success){
                $params['path'] = 'https://' . $img_url;
                $params['driver'] = 'tencentoss';
                if ($file_add = Attachment_Model::create($params)) {
                    // 返回结果
                    return json_encode([
                        'code'    => 0,
                        'info'    => $params['name'] . '上传成功',
                        'id'      => $file_add['id'],
                        'path'    => $params['path'],
                        'state'   => "SUCCESS",      // 上传状态，上传成功时必须返回"SUCCESS" 兼容百度
                        'title'   => $params['name'],// 附件名，兼容百度ueditor
                        'url'     => $params['path'],// 返回的地址，兼容百度ueditor和editormd
                        'error'   => 0,              // 兼容kindeditor
                        'success' => 1,              // 兼容editormd
                        'message' => $params['name'],// 附件名，兼容editormd和kindeditor
                    ],JSON_UNESCAPED_UNICODE);
                } else {
                    return json_encode([
                        'code'    => -1,
                        'info'    => '上传成功,写入数据库失败',
                        'state'   => '上传成功,写入数据库失败', //兼容百度ueditor
                        'error'   => 1,                       //兼容kindeditor
                        'success' => 0,                       //兼容editormd
                        'message' => '上传成功,写入数据库失败', //兼容editormd
                    ],JSON_UNESCAPED_UNICODE);
                }
            }else{
                return json_encode([
                    'code'    => -1,
                    'info'    => '上传失败',
                    'state'   => '上传失败', //兼容百度ueditor
                    'error'   => 1,         //兼容kindeditor
                    'success' => 0,         //兼容editormd
                    'message' => '上传失败', //兼容editormd和kindeditor
                ]);
            }
		} catch (\Exception $e) {
            return json_encode([
                'code'    => -1,
                'info'    => '上传失败:' . $e->getMessage(),
                'state'   => '上传失败:' . $e->getMessage(), //兼容百度ueditor
                'error'   => 1,                             //兼容kindeditor
                'success' => 0,                             //兼容editormd
                'message' => '上传失败:' . $e->getMessage(), //兼容editormd和kindeditor
            ]);
        }
    }
    /**
     * name 钩子(行为)名称
     * description 钩子描述
     * type 类型(1:视图,2:控制器)
     * system 是否系统
     * status 状态
     * @HooksAnotation(description="删除oss附件",type="2")
     * @return [type] [description]
     */
    public function DeleteOss($params = [])
    {
        // 判断是否调用腾讯云的
        if(sys_config('upload_driver') !== 'tencentoss'){
            return '';
        }
        $this->init(); 
        try {
            $arr = parse_url($params['path']);
            $key = ltrim($arr['path'],'/');
            $bucket = $this->config['bucket'] . '-' . $this->config['APPID']; //存储桶，格式：BucketName-APPID
            $cosClient = new \Qcloud\Cos\Client(
                array(
                    'region' => $this->config['region'],
                    'schema' => 'https',//协议头部，默认为http
                    'credentials'=> array(
                        'secretId'  => $this->config['SecretId'],
                        'secretKey' => $this->config['SecretKey']
                    )
                )
            );
            $result = $cosClient->deleteObject(array(
                'Bucket' => $bucket,
                'Key' => $key,
            ));
            // 请求成功
            return true;
        } catch (\Exception $e) {
            // 请求失败
            // echo($e);
            return false;
        }
    }
    protected function isLogin()
    {
        if (is_login() > 0) {
            $this->isadmin  = 1;
            $this->admin_id = is_login();
        } elseif (home_user::instance()->isLogin()) {
            $this->user_id = home_user::instance()->id;
            $this->groupid = home_user::instance()->groupid ? home_user::instance()->groupid : 8;
        } else {
            $this->admin_id = 0;
            $this->user_id = 0;
        }
    }
    protected function implode_attr($array = [])
    {
        $result = [];
        foreach ($array as $key => $value) {
            $result[] = $key . ':' . $value;
        }
        return empty($result) ? '' : implode(PHP_EOL, $result);
    }
}
